﻿using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Batman.Cms.Core.Utils
{
    public class JwtTokenUtil
    {
        /// <summary>
        /// 获取token方法
        ///
        /// </summary>
        /// <param name="secret">秘钥</param>
        /// <param name="issuer"></param>
        /// <param name="audience"></param>
        /// <param name="claims">身份信息</param>
        /// <param name="expiresIn">过期时间，单位分钟</param>
        /// <param name="algorithms">加密算法 参考静态类SecurityAlgorithms</param>
        /// <returns></returns>
        public static string GetToken(
            string secret,
            string issuer,
            string audience,
            IEnumerable<Claim> claims,
            int expiresIn = 30,
            string algorithms = SecurityAlgorithms.HmacSha256)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, algorithms);

            //claims = new[] { new Claim(ClaimTypes.Name, "wolf") };

            //IdentityModelEventSource.ShowPII = true;

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(expiresIn),
                signingCredentials: creds);

            var tokenHander = new JwtSecurityTokenHandler();
            var t = tokenHander.WriteToken(token);
            return t;
        }
    }
}
